package com.itany.mall.service.proxy;

import java.util.List;

import com.itany.mall.entity.Product;
import com.itany.mall.exception.ProductNameExistsException;
import com.itany.mall.exception.ProductNotFoundException;
import com.itany.mall.exception.ProductTypeNotFoundException;
import com.itany.mall.exception.ServiceException;
import com.itany.mall.factory.Autowired;
import com.itany.mall.factory.Component;
import com.itany.mall.jdbc.transaction.TransactionManager;
import com.itany.mall.service.ProductService;
import com.itany.mall.vo.PageInfo;

@Component("productServiceProxy")
public class ProductServiceProxy implements ProductService {
	@Autowired
	private TransactionManager tm;

	@Autowired("productServiceImpl")
	private ProductService impl;

	@Override
	public List<Product> findAll() throws ServiceException {
		try {
			tm.beginTransaction();
			List<Product> list = impl.findAll();
			tm.commit();
			return list;
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
			throw new ServiceException();
		}
	}

	@Override
	public void addProduct(String name, double price, long typeId)
			throws ProductNameExistsException, ProductTypeNotFoundException, ServiceException {
		try {
			tm.beginTransaction();
			impl.addProduct(name, price, typeId);
			tm.commit();
		} catch (ProductNameExistsException e) {
			tm.rollback();
			throw e;
		} catch (ProductTypeNotFoundException e) {
			tm.rollback();
			throw e;
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
			throw new ServiceException();
		}
	}

	@Override
	public Product findById(long productId) throws ProductNotFoundException, ServiceException {
		try {
			tm.beginTransaction();
			Product p = impl.findById(productId);
			tm.commit();
			return p;
		} catch (ProductNotFoundException e) {
			tm.rollback();
			throw e;
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
			throw new ServiceException();
		}
	}

	@Override
	public PageInfo<Product> findAll(int pageNo, int pageSize) throws ServiceException {
		try {
			tm.beginTransaction();
			PageInfo<Product> page = impl.findAll(pageNo, pageSize);
			tm.commit();
			return page;
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
			throw new ServiceException();
		}
	}

}
